
<script setup>import { ref, getCurrentInstance, computed, onUnmounted } from 'vue'
import { showFailToast, showSuccessToast } from 'vant'
import router from "../router/router.js"

const phone = ref('')
const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const code = ref('')
const gender = ref(0)
const birthDate = ref('') // 存储完整的出生日期字符串
const currentDate = ref([new Date().getFullYear().toString(), '01', '01'])// 日期选择器的默认值
const showDatePicker = ref(false) // 控制日期选择器弹窗显示
const isCountingDown = ref(false)
const countdown = ref(60)
let timer = null


// 返回上一页方法
const goBack = () => {
  router.go(-1)
}

// 添加性别选择相关数据
const showGenderPicker = ref(false)
const genderText = ref('未知')

const genderOptions = [
  { text: '未知', value: 0 },
  { text: '男', value: 1 },
  { text: '女', value: 2 }
]

const { proxy } = getCurrentInstance()

// 验证手机号是否为11位
const isValidPhone = computed(() => {
  return phone.value && phone.value.length === 11
})

const countdownText = computed(() => {
  return isCountingDown.value ? `${countdown.value}秒后重新发送` : '发送验证码'
})

// 在 script setup 中添加密码强度检测函数
const checkPasswordStrength = (password) => {
  let strength = 0;
  let messages = [];

  // 检查长度
  if (password.length >= 8) {
    strength += 1;
  } else {
    messages.push('密码至少8位');
  }

  // 检查是否包含数字
  if (/\d/.test(password)) {
    strength += 1;
  } else {
    messages.push('需要包含数字');
  }

  // 检查是否包含小写字母
  if (/[a-z]/.test(password)) {
    strength += 1;
  } else {
    messages.push('需要包含小写字母');
  }

  // 检查是否包含大写字母
  if (/[A-Z]/.test(password)) {
    strength += 1;
  } else {
    messages.push('需要包含大写字母');
  }

  // 检查是否包含特殊字符
  if (/[^A-Za-z0-9]/.test(password)) {
    strength += 1;
  } else {
    messages.push('需要包含特殊字符');
  }

  return { strength, messages };
}

// 计算密码强度等级
const passwordStrength = computed(() => {
  if (!password.value) return { level: 0, text: '', color: '' };

  const { strength } = checkPasswordStrength(password.value);

  if (strength <= 2) {
    return { level: 1, text: '弱', color: '#f56c6c' };
  } else if (strength <= 3) {
    return { level: 2, text: '中', color: '#e6a23c' };
  } else if (strength <= 4) {
    return { level: 3, text: '强', color: '#67c23a' };
  } else {
    return { level: 4, text: '很强', color: '#409eff' };
  }
});

// 生成年份选项（最近100年）
const yearOptions = computed(() => {
  const currentYear = new Date().getFullYear()
  const options = []
  for (let i = currentYear; i >= currentYear - 100; i--) {
    options.push({ text: `${i}年`, value: i.toString() })
  }
  return options
})

// 生成月份选项
const monthOptions = computed(() => {
  const options = []
  for (let i = 1; i <= 12; i++) {
    options.push({ text: `${i}月`, value: i.toString().padStart(2, '0') })
  }
  return options
})

// 判断是否为闰年
const isLeapYear = (year) => {
  return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)
}

// 根据年份和月份获取该月的天数
const getDaysInMonth = (year, month) => {
  const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

  if (month === 2 && isLeapYear(year)) {
    return 29
  }

  return daysInMonth[month - 1]
}

// 生成日期选项（根据选择的年份和月份动态生成）
const dayOptions = computed(() => {
  let selectedYear = currentDate.value[0] ? parseInt(currentDate.value[0]) : new Date().getFullYear()
  let selectedMonth = currentDate.value[1] ? parseInt(currentDate.value[1]) : 1

  const daysInSelectedMonth = getDaysInMonth(selectedYear, selectedMonth)

  const options = []
  for (let i = 1; i <= daysInSelectedMonth; i++) {
    options.push({ text: `${i}日`, value: i.toString().padStart(2, '0') })
  }
  return options;
})

// 日期选择器的列
const dateColumns = computed(() => [
  yearOptions.value,
  monthOptions.value,
  dayOptions.value
])

// 当年份或月份改变时，更新日期选项并调整选中的日期
const onDateChange = (event) => {
  // 从事件对象中获取选中的值数组（格式：[年份, 月份, 日期]）
  const values = event.selectedValues;

  // 确保 values 是有效的数组
  if (!Array.isArray(values) || values.length !== 3) {
    console.error('无效的日期选择值:', values);
    return;
  }

  // 更新 currentDate.value 为选中的值
  currentDate.value = values;

  // 检查日期是否超过当月最大天数（处理月份切换时日期无效的情况）
  const year = parseInt(values[0]);
  const month = parseInt(values[1]);
  const day = parseInt(values[2]);
  const daysInMonth = getDaysInMonth(year, month);

  if (day > daysInMonth) {
    // 若日期超出当月最大天数，自动调整为当月最后一天
    currentDate.value = [
      values[0],
      values[1],
      daysInMonth.toString().padStart(2, '0')
    ];
  }
}

// 性别选择确认方法
const onGenderConfirm = (valueObj) => {
  const selectedValue = valueObj.selectedValues[0]
  const selectedItem = genderOptions.find(item => item.value === selectedValue)

  if (selectedItem) {
    gender.value = selectedItem.value
    genderText.value = selectedItem.text
  }

  showGenderPicker.value = false
}

// 性别选择取消方法
const onGenderCancel = () => {
  showGenderPicker.value = false
}

const sendCode = () => {
  if (!phone.value) {
    showFailToast('请输入手机号')
    return
  }

  // 验证手机号是否为11位
  if (!isValidPhone.value) {
    showFailToast('请输入正确的11位手机号')
    return
  }

  proxy.$axios.post('/user/sendCode', {
    phone: phone.value
  }).then(ServerData => {
    if (ServerData.data.code === 0) {
      showSuccessToast("验证码发送成功")
      console.log(ServerData.data.data)
      startCountdown()
    } else {
      showFailToast("验证码发送失败")
    }
  }).catch(error => {
    console.log("请求发生异常", error)
    showFailToast("验证码发送失败,请稍后重试")
  })
}

// 显示日期选择器
const showDatePopup = () => {
  showDatePicker.value = true
}

// 确认选择日期
const confirmDate = (event) => {
  const values = event.selectedValues; // 从事件对象中获取值
  birthDate.value = `${values[0]}-${values[1]}-${values[2]}`;
  showDatePicker.value = false;
};

// 取消选择日期
const cancelDate = () => {
  showDatePicker.value = false
}

// 注册方法
const register = () => {
  // 验证输入
  if (!phone.value) {
    showFailToast('请输入手机号')
    return
  }

  // 验证手机号是否为11位
  if (!isValidPhone.value) {
    showFailToast('请输入正确的11位手机号')
    return
  }

  if (!username.value) {
    showFailToast('请输入用户名')
    return
  }
  if (!password.value) {
    showFailToast('请输入密码')
    return
  }

  // 添加密码强度验证
  const { strength, messages } = checkPasswordStrength(password.value);
  if (strength < 3) { // 要求至少中等强度
    showFailToast('密码强度不足: ' + messages.join(', '))
    return
  }

  if (password.value !== confirmPassword.value) {
    showFailToast('两次输入的密码不一致')
    return
  }
  if (!code.value) {
    showFailToast('请输入验证码')
    return
  }
  if (gender.value !== 0 && gender.value !== 1 && gender.value !== 2) {
    showFailToast('请选择性别')
    return
  }
  if (!birthDate.value) {
    showFailToast('请选择出生日期')
    return
  }

  proxy.$axios.post('/user/register', {
    phone: phone.value,
    username: username.value,
    password: password.value,
    code: parseInt(code.value),
    gender: gender.value,
    birth_date: birthDate.value
  }).then(ServerData => {
    if (ServerData.data.code === 0) {
      showSuccessToast("注册成功")
      showSuccessToast("一秒后跳转登录页面")
      setTimeout(() => {
        router.push('/login?loginType=password')
      }, 1000)
    }else if (ServerData.data.code === 2) {
      showFailToast(ServerData.data.msg)
    }
    else {
      console.log(ServerData.data)
      showFailToast("验证码错误")
    }
  }).catch(error => {
    console.log("请求发生异常", error)
    showFailToast("注册失败,请稍后重试")
  })
}

// 开始倒计时
const startCountdown = () => {
  isCountingDown.value = true
  countdown.value = 60

  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      stopCountdown()
    }
  }, 1000)
}

// 停止倒计时
const stopCountdown = () => {
  isCountingDown.value = false
  clearInterval(timer)
  timer = null
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<template>
  <div style="margin-top:20px; display: flex; justify-content: center">
    <van-icon name="arrow-left" @click="goBack" style="position: absolute; left: 20px; font-size: 24px;" />
    注册
  </div>

  <!-- 内容区域，留出标题空间 -->
  <div style="margin-top: 1px; padding: 20px;">
    <van-cell-group>
      <van-field
          v-model="phone"
          type="digit"
          label="手机号"
          placeholder="请输入手机号"
      />
      <van-field
          v-model="username"
          label="用户名"
          placeholder="请输入用户名"
      />
      <van-field
          v-model="password"
          type="password"
          label="密码"
          placeholder="请输入密码"
      />
      <van-field
          v-model="confirmPassword"
          type="password"
          label="确认密码"
          placeholder="请输入确认密码"
      />
      <!-- 添加密码强度显示 -->
      <div v-if="password" style="padding: 5px 16px;">
        <div style="display: flex; align-items: center; margin-bottom: 5px;">
          <span style="font-size: 12px; margin-right: 10px;">密码强度:</span>
          <span :style="{ color: passwordStrength.color, fontSize: '12px' }">
        {{ passwordStrength.text }}
      </span>
        </div>
        <div style="display: flex; height: 6px; border-radius: 3px; overflow: hidden;">
          <div
              v-for="i in 4"
              :key="i"
              :style="{
          flex: 1,
          backgroundColor: i <= passwordStrength.level ? passwordStrength.color : '#ebeef5',
          marginRight: i < 4 ? '2px' : '0'
        }"
          ></div>
        </div>
      </div>

      <!-- 性别选择弹窗 -->
      <van-popup v-model:show="showGenderPicker" position="bottom" round>
        <van-picker
            :columns="genderOptions"
            :default-index="gender"
            @confirm="onGenderConfirm"
            @cancel="onGenderCancel"
            show-toolbar
            title="选择性别"
        />
      </van-popup>

      <!-- 出生日期选择 -->
      <van-cell title="出生日期" is-link @click="showDatePopup">
        <span v-if="birthDate">{{ birthDate }}</span>
        <span v-else style="color: #999;">请选择出生日期</span>
      </van-cell>

      <van-field
          v-model="code"
          type="digit"
          label="验证码"
          placeholder="请输入验证码"
      >
        <template #button>
          <van-button
              size="small"
              type="primary"
              :disabled="isCountingDown"
              @click="sendCode"
          >
            {{ countdownText }}
          </van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div style="display: flex; justify-content: center; margin-top: 30px;">
      <van-button
          size="normal"
          type="primary"          style="border-radius: 20px; width: 260px"
          @click="register"
      >
        注册
      </van-button>
    </div>
  </div>

  <!-- 出生日期选择弹窗 -->
  <van-popup v-model:show="showDatePicker" position="bottom" round>
    <van-picker
        :columns="dateColumns"
        v-model="currentDate"
        @change="onDateChange"
        @confirm="confirmDate"
        @cancel="cancelDate"
        show-toolbar
        title="选择出生日期"
    />
  </van-popup>
</template>
<style scoped>.gender-radio-group {
  display: flex;
  justify-content: left;
  gap: 5px;
  min-width: 150px; /* 设置最小宽度 */
}

.gender-radio-item {
  white-space: normal;
  overflow: visible;
  text-overflow: clip;
  margin-right: 5px;
  flex-grow: 1; /* 根据内容自动调整宽度 */
}
</style>